package com.chyb.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/*测试限流和热点*/
@Slf4j
@RestController
public class RateLimitController {
    @GetMapping("/rateLimit/byUrl")
    public String byUrl() {
        return "按rest地址限流测试OK";
    }

    @GetMapping("/rateLimit/byResource/{p1}")
    @SentinelResource(value = "testSentinelResource", blockHandler = "handlerSentinelResource", fallback = "handlerEx")
    public String byResource(@PathVariable("p1") Integer p1) {
        if (p1 == 0) {
            throw new RuntimeException("p1为零，程序异常");
        }
        return "我使用了SentinelResource注解";
    }

    public String handlerSentinelResource(@PathVariable("p1") Integer p1, BlockException exception) {
        log.error("sentinel配置自定义限流了:{}", exception);
        return "sentinel配置自定义限流了";
    }

    public String handlerEx(@PathVariable("p1") Integer p1, Throwable exception) {
        log.info("程序异常{}", exception);
        return "程序逻辑异常了" + "\t" + exception.getMessage();
    }


    /*测试热点参数*/
    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey",blockHandler = "dealHandler_testHotKey")
    public String testHotKey(@RequestParam(value = "p1",required = false) String p1,

                             @RequestParam(value = "p2",required = false) String p2){
        return "------testHotKey";
    }
    public String dealHandler_testHotKey(String p1,String p2,BlockException exception)
    {
        return "-----dealHandler_testHotKey";
    }
}
